#!/bin/bash
# -*- coding: utf-8 -*-
#Filename:gitlab_backup.sh
#Author:SuJunQuan
#Email:sujunquan@qq.com
#Date:2016-11-22
#Desc:Every day 2:00 auto backup gitlab to /data/gitlab_backup

#定义相关路径变量
gitlab_home=/opt/gitlab-8.5.7-0
gitlab_backip_dir=/data/gitlab_backup
git_backup_path=/opt/gitlab-8.5.7-0/apps/gitlab/htdocs/

#判断备份目录是否存在
[ -d $gitlab_backup_dir ] || [ mkdir $gitlab_backup_dir ]

#判断是否存在git用户
if [ ! id git > /dev/null 2>&1 ];then
    echo "The git user not exist"
	exit 1
fi
#判断postgresql数据库是否在运行状态
if [ ! netstat -tnlp |grep -w 5432 ];then
	$gitlab_home/ctlscript.sh restart postgresql
fi
#判断gitlab_workh是否在运行状态
if [ ! netstat -tnlp |grep -w 8181 ];then
	$gitlab_home/ctlscript.sh restart 
fi

#判断gitlab运行状态是否都为running
#stat=`$gitlab_home/ctlscript.sh status|awk '{print $NF}'`
#sleep 5
#for s in ${stat[*]}
#do
#	if [ $s != 'running' ];then
#		$gitlab_home/ctlscript.sh restart
		break
#	fi
#done

#使用bitnami PATH
PATH="/opt/gitlab-8.5.7-0/nodejs/bin:/opt/gitlab-8.5.7-0/apps/gitlabci/gitlabci-multirunner:/opt/gitlab-8.5.7-0/apps/gitlab/gitlab-shell/bin:/opt/gitlab-8.5.7-0/redis/bin:/opt/gitlab-8.5.7-0/sqlite/bin:/opt/gitlab-8.5.7-0/python/bin:/opt/gitlab-8.5.7-0/perl/bin:/opt/gitlab-8.5.7-0/git/bin:/opt/gitlab-8.5.7-0/ruby/bin:/opt/gitlab-8.5.7-0/mysql/bin:/opt/gitlab-8.5.7-0/php/bin:/opt/gitlab-8.5.7-0/postgresql/bin:/opt/gitlab-8.5.7-0/apache2/bin:/opt/gitlab-8.5.7-0/common/bin:$PATH"

#进入能备份命令bundle目录
cd $git_backup_path

#使用git用户备份，打印备份日志
sudo -u git -H bundle exec bin/rake gitlab:backup:create RAILS_ENV=production && \
echo "`date +%F-%T` gitlab backup success" >> $gitlab_backup_dir/gitlab_backup.log
